package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.backend.dto.Result;
import org.example.backend.entity.Leader;
import org.example.backend.entity.Order;
import org.example.backend.entity.Product;
import org.example.backend.entity.view.StockWarningView;
import org.example.backend.mapper.LeaderMapper;
import org.example.backend.mapper.OrderMapper;
import org.example.backend.mapper.ProductMapper;
import org.example.backend.mapper.view.StockWarningViewMapper;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 * 提供管理员相关功能
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private LeaderMapper leaderMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private StockWarningViewMapper stockWarningViewMapper;

    /**
     * 获取管理员仪表盘数据
     * @return 仪表盘数据
     */
    @GetMapping("/dashboard")
    public ResponseEntity<Result<Map<String, Object>>> getDashboardData() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> statistics = new HashMap<>();
        
        // 1. 商品总数
        Long productCount = productMapper.selectCount(null);
        statistics.put("productCount", productCount);
        
        // 2. 订单总数
        Long orderCount = orderMapper.selectCount(null);
        statistics.put("orderCount", orderCount);
        
        // 3. 团长总数
        Long leaderCount = leaderMapper.selectCount(null);
        statistics.put("leaderCount", leaderCount);
        
        // 4. 库存预警数量
        Long stockWarningCount = stockWarningViewMapper.selectCount(null);
        statistics.put("stockWarningCount", stockWarningCount);
        
        // 5. 库存预警列表
        List<StockWarningView> stockWarningList = stockWarningViewMapper.selectList(
                Wrappers.<StockWarningView>lambdaQuery()
                        .orderByAsc(StockWarningView::getStock)
                        .last("LIMIT 5")
        );
        
        // 6. 最近订单列表
        List<Order> recentOrderList = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                        .orderByDesc(Order::getCreateTime)
                        .last("LIMIT 5")
        );
        
        result.put("statistics", statistics);
        result.put("stockWarningList", stockWarningList);
        result.put("recentOrderList", recentOrderList);
        
        return ResponseUtil.success(result);
    }
} 